package com.xudow.app.ui.task;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;

import com.activeshare.edu.ucenter.common.messages.Message;
import com.xudow.app.Config;
import com.xudow.app.XApplication;
import com.xudow.app.util.rest.XRestTemplate;

import org.apache.http.entity.ContentType;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.ContentCodingType;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;

import static com.xudow.app.util.LogUtils.LOGE;
import static com.xudow.app.util.LogUtils.makeLogTag;

/**
 * 新建错题Task
 *
 * @author lukecheng
 */
public class ClazzMistakeCreateTask extends AsyncTask<HashMap<String, Object>, Void, Void> {
    private static final String TAG = makeLogTag(ClazzMistakeCreateTask.class);

    private static final String CLASS_MISTAKE_CREATE_URL = Config.BASE_URL + Config.CLASS_MISTAKE_CREATE_URL;

    public static final int SUCCESS = 0;
    public static final int ERROR = 1;
    public static final int ERROR_WITH_MESSAGE = 2;

    private Context context;
    private Handler handler;

    public ClazzMistakeCreateTask(Context context, Handler handler) {
        this.context = context;
        this.handler = handler;
    }

    private void sendErrorMessage(String msg) {
        android.os.Message message = new android.os.Message();
        message.what = ERROR;

        if (null != msg) {
            Bundle data = new Bundle();
            data.putString("errMessage", msg);
            message.setData(data);
        }

        handler.sendMessage(message);
    }

    private void sendSuccessMessage() {
        android.os.Message message = new android.os.Message();
        message.what = SUCCESS;
        handler.sendMessage(message);
    }

    @Override
    protected Void doInBackground(HashMap<String, Object>... parameters) {
        String studentid = (String) parameters[0].get("studentid");
        String subjectid = (String) parameters[0].get("subjectid");
        String title = (String) parameters[0].get("title");
        String remark = (String) parameters[0].get("remark");
        List<String> corrects = (List<String>) parameters[0].get("correct");
        List<String> errors = (List<String>) parameters[0].get("error");

        LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
        map.add("studentid", studentid);
        map.add("subjectid", subjectid);
        try {
            map.add("title", new String(title.getBytes(), "ISO-8859-1"));
            map.add("remark", new String(remark.getBytes(), "ISO-8859-1"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        if (null != parameters[0].get("wrongid")) {
            map.add("wrongid", parameters[0].get("wrongid"));
        }

        if (corrects.size() > 0) {
            for (int i = 0; i < corrects.size(); i++) {
                map.add("correct_" + i, new FileSystemResource(corrects.get(i)));
            }
        }

        if (errors.size() > 0) {
            for (int i = 0; i < errors.size(); i++) {
                map.add("error_" + i, new FileSystemResource(errors.get(i)));
            }
        }

        HttpHeaders headers = new HttpHeaders();
        headers.set("Accept-Charset", "utf-8");
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity =
                new HttpEntity<LinkedMultiValueMap<String, Object>>(map, headers);

        XApplication application = (XApplication) context.getApplicationContext();

        XRestTemplate restTemplate = new XRestTemplate(application.getCookieStore(), context);
        restTemplate.getMessageConverters()
                .add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
        restTemplate.reInitMessageConverter();

        try {
            ResponseEntity<Message> response = restTemplate.exchange(
                    CLASS_MISTAKE_CREATE_URL, HttpMethod.POST, requestEntity, Message.class);

            Message result = response.getBody();

            if (result != null) {
                if (result.getResult().equals("0")) {
                    sendSuccessMessage();
                } else if (result.getResult().equals("1")) {
                    sendErrorMessage(result.getErrorMessage());
                }
            } else {
                sendErrorMessage(null);
            }
        } catch (Exception e) {
            LOGE(TAG, e.getMessage());

            sendErrorMessage(null);
        }

        return null;
    }
}
